<template>
  <div class="home">
    <a @click="jump">A跳转</a>
    <KButtonArea>
      <KButton
        type="primary"
        open-type="getUserInfo"
        @getuserinfo="getPhonenumber"
        >获取头像</KButton
      >
      <KButton
        type="primary"
        open-type="getPhoneNumber"
        @getphonenumber="getPhonenumber"
      >
        getUserInfo
      </KButton>
      <KButton type="primary" :loading="true">零度的田</KButton>
      <KButton type="primary" :disabled="true">小程序开发</KButton>
      <KButton>页面次要操作</KButton>
      <KButton type="warn">警告类操作</KButton>
      <KButton type="warn" :loading="true">警告类操作</KButton>
      <KButton type="warn" :disabled="true">警告类操作</KButton>
    </KButtonArea>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src
import { KButton } from "kbone-ui";

import { MobileLoginParam, oauthLogin, OAuthResultParam } from "@api/member";

@Component({
  components: {
    HelloWorld
  }
})
export default class My extends Vue {
  private code: string = "";

  created() {
    this.getCode();
  }

  jump() {
    window.location.href = "/home";
  }

  getCode() {
    wx.login({
      success: async (res: WechatMiniprogram.LoginSuccessCallbackResult) => {
        this.code = res.code;
      }
    });
  }

  async getPhonenumber(e: any) {
    console.log(e);
    const detail = e.detail as WechatMiniprogram.GetUserInfoSuccessCallbackResult;

    wx.checkSession({
      success() {
        console.log("ssss");
      },
      fail() {
        console.log("fff");
      }
    });

    this.login(detail);
  }

  async login(detail: WechatMiniprogram.GetUserInfoSuccessCallbackResult) {
    const param: OAuthResultParam = {
      code: this.code,
      encryptedData: detail.encryptedData,
      iv: detail.iv
    };

    const result = await oauthLogin("miniapp", param);

    console.log(result);

    if (result.isSuccess) {
      wx.setStorageSync("user", JSON.stringify(result.data));
    }

    this.getCode();
  }
}
</script>
